package com.java9s.goldchit.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.java9s.goldchit.beans.Address;

public class AddressDaoImpl implements AddressDao {

	private SessionFactory sessionFactory;
	private Session session;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public void saveAddress(Address address) {
		session = getSessionFactory().openSession();
		if (address != null) {
			session.clear();
			session.saveOrUpdate(address);
			session.flush();
		}
		session.close();
	}

	@Override
	public Address getAddressOfCustomer(int customerId) {
		session = getSessionFactory().openSession();
		Criteria criteria = session.createCriteria(Address.class);
		criteria.add(Restrictions.like("customerId",
				Integer.valueOf(customerId)));
		List addressList = criteria.list();
		Address address = (Address) addressList.get(0);
		session.close();
		return address;

	}

	@Override
	public Address getAddress(int addressId) {
		session = getSessionFactory().openSession();
		return (Address) session.get(Address.class, Integer.valueOf(addressId));
	}

}
